import { apiService } from "@service/index";
import { LoginFormState } from "@pages/login";
import { saveCredential } from "@slice/credential";

const authEndpoints = apiService.injectEndpoints({
  endpoints: (build) => ({
    // 登录注册
    login: build.mutation<LoginResponse, LoginFormState>({
      // 请求的基本配置
      query: (body) => ({ url: "/authorizations", method: "post", body }),
      // 请求发送开始执行
      async onQueryStarted(arg, api) {
        // promise 对象, 请求对应的 promise 对象
        // 等待请求发送完成
        let response = await api.queryFulfilled;
        // 登录成功之后要保存用户的登录凭据
        api.dispatch(saveCredential(response.data.data));
      },
    }),
    // 发送手机验证码
    sendMsgCode: build.query<GeekResponse<null>, string>({
      query: (mobile) => ({ url: `/sms/codes/${mobile}` }),
    }),
  }),
});

export const { useLoginMutation, useLazySendMsgCodeQuery } = authEndpoints;
